package com.kyzh.core.activities

import android.content.Context
import android.content.Intent
import android.content.res.ColorStateList
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.webkit.*
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.setPadding
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.GridLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.module.LoadMoreModule
import com.chad.library.adapter.base.viewholder.BaseDataBindingHolder
import com.google.android.material.tabs.TabLayout
import com.gushenge.core.base.activity.BaseActivity
import com.gushenge.core.beans.LiveRoomBean
import com.gushenge.core.requests.LiveRequest
import com.kyzh.core.R
import com.kyzh.core.pager.weal.live.LiveActivity
import com.kyzh.core.databinding.ActivityMyCollectBinding
import com.kyzh.core.databinding.ItemFragmentLiveBinding
import com.kyzh.core.databinding.TablayoutGuanzhuTextBinding
import com.kyzh.core.utils.im.TUIUtils
import com.kyzh.core.utils.setVisibility
import com.gushenge.core.toast
import com.tencent.imsdk.v2.V2TIMGroupInfoResult
import com.tencent.imsdk.v2.V2TIMManager
import com.tencent.imsdk.v2.V2TIMValueCallback
import kotlinx.android.synthetic.main.activity_my_collect.*
import kotlinx.android.synthetic.main.activity_vip.*
import kotlinx.android.synthetic.main.titlebar.view.*

class MyCollectActivity : BaseActivity() {
    companion object{
        @JvmStatic
        fun start(context: Context) {
            val starter = Intent(context,MyCollectActivity ::class.java)
//                .putExtra()
            context.startActivity(starter)
        }
    }
    private val adapter  = Adapter()
    private var databind: ActivityMyCollectBinding ? = null
    private var tabs = arrayListOf<String>("直播","我的群聊")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        databind=  DataBindingUtil.setContentView(this,R.layout.activity_my_collect)
        databind?.lifecycleOwner = this
        initView()
    }

    fun initView(){
//        initWeb()
        databind?.apply {
//            inTitle.getClose().setOnClickListener {
//                exit()
//            }
            rev.layoutManager = GridLayoutManager(this@MyCollectActivity,2)
            rev.adapter = adapter
            val inflate = LayoutInflater.from(this@MyCollectActivity).inflate(R.layout.empty, null)
            val image = inflate.findViewById<ImageView>(R.id.image)
            image.setImageResource(R.drawable.empty_live)
            val tv1 = inflate.findViewById<TextView>(R.id.tv1)
            tv1.text = "快去关注你感兴趣的直播吧～～～"
            tv1.setTextColor(Color.parseColor("#FFCFCFCF"))
            adapter.setEmptyView(inflate)
            tabs.forEach {
                tab.addTab(tab.newTab().apply {

                    customView = null
                    val inflate = DataBindingUtil.inflate<TablayoutGuanzhuTextBinding>(
                        LayoutInflater.from(this@MyCollectActivity),
                        R.layout.tablayout_guanzhu_text,
                        null,
                        false
                    )
                    tag = it
                    val findViewById = inflate.root.findViewById<TextView>(R.id.tv)
                    findViewById.text = it
                    customView = inflate.root
                    customView?.setPadding(0)
                })
            }
            LiveRequest.getShouCang{
                adapter.setNewInstance(this)
            }
            tab.getTabAt(0)?.select()

            tab.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener{
                override fun onTabSelected(tab: TabLayout.Tab?) {
                    val findViewById = tab?.customView?.findViewById<TextView>(R.id.tv)
                    findViewById?.setTextColor(resources.getColor(R.color.font_33))
                    findViewById?.textSize = 16f
                    if (tab != null) {
                        if(tab.tag == tabs[1]){
                            web.setVisibility(true)
                            rev.setVisibility(false)
                            web.reload()
                        }else{
                            web.setVisibility(false)
                            rev.setVisibility(true)
                            LiveRequest.getShouCang{
                                adapter.setNewInstance(this)
                            }
                        }
                    }
                }

                override fun onTabUnselected(tab: TabLayout.Tab?) {
                    val findViewById = tab?.customView?.findViewById<TextView>(R.id.tv)
                    findViewById?.setTextColor(resources.getColor(R.color.font_99))
                    findViewById?.textSize = 14f
                }

                override fun onTabReselected(tab: TabLayout.Tab?) {
                    val findViewById = tab?.customView?.findViewById<TextView>(R.id.tv)
                    findViewById?.setTextColor(resources.getColor(R.color.font_33))
                    findViewById?.textSize = 16f
                    if (tab != null) {
                        if(tab.tag == tabs[1]){
                            web.setVisibility(true)
                            rev.setVisibility(false)
                            web.reload()
                        }else{
                            web.setVisibility(false)
                            rev.setVisibility(true)
                            LiveRequest.getShouCang{
                                adapter.setNewInstance(this)
                            }
                        }
                    }
                }
            })
        }
    }
//    @SuppressLint("SetJavaScriptEnabled")
//    private fun initWeb() {
//        val webSettings = web.settings
//        webSettings.allowFileAccess = true// 设置允许访问文件数据
//        webSettings.setSupportZoom(true)
//        webSettings.builtInZoomControls = true
//        webSettings.cacheMode = WebSettings.LOAD_NO_CACHE
//        webSettings.domStorageEnabled = true
//        webSettings.databaseEnabled = true
//        webSettings.allowFileAccessFromFileURLs=true
//        // 关键性代码，这里要给webview添加这行代码，才可以点击之后正常播放音频。记录一下。
//        webSettings.mediaPlaybackRequiresUserGesture = false
//        webSettings.setAppCacheEnabled(false)
//
//        //设置WebView属性，能够执行Javascript脚本
//        webSettings.javaScriptEnabled = true
//        web.webChromeClient = object : WebChromeClient() {
//            override fun onProgressChanged(view: WebView, newProgress: Int) {
//            }
//
//            override fun onReceivedTitle(view: WebView?, title: String?) {
//                super.onReceivedTitle(view, title)
////                if (name != getString(R.string.privacyPolicy) && name != getString(R.string.registerAgreement)) {
////                    titleView.setText(title ?: "")
////                }
//            }
//            override fun onJsAlert(
//                view: WebView?,
//                url: String?,
//                message: String?,
//                result: JsResult?
//            ): Boolean {
//                when{
//                    message == getString(R.string.winningRecord) -> {
//                        result?.cancel()
//                        startActivity<ZJLSActivity>()
//                        return true
//                    }
//                    message?.startsWith("gid")?:false ->{
//                        result?.cancel()
//                        startGameDetailActivity(message?.substring(4))
//                        return true
//                    }
//                    else -> {
//                        message?.toast()
//                        result?.cancel()
//                        return true
//                    }
//                }
//                return true
//            }
//
//        }
//
//        web.webViewClient = object : WebViewClient() {
//            override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler?, error: SslError?) {
//                super.onReceivedSslError(view, handler, error)
//                handler?.proceed()
//            }
//            override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
//                try {
//                    if (url.startsWith("http")) {
//                        //处理http和https开头的url
//                        val extraHeaders = HashMap<String,String>()
//                        extraHeaders["Referer"] = Base.BASEURL
//                        view.loadUrl(url, extraHeaders)
//                        return true
//                    }else{
//                        browse(url)
//                        return true
//                    }
//                } catch (e: Exception) {
//                    //防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
//                    return false
//                }
//            }
//
//            override fun onPageFinished(view: WebView, url: String) {
//                val js = "javascript:(function() {document.getElementById(\"j_page_header\").style.display=\'none\';" + "})()"
//                view.loadUrl(js)
//                super.onPageFinished(view, url)
//            }
//        }
//
//        val instance = CookieManager.getInstance()
//        instance.setAcceptThirdPartyCookies(web,true)
//        web.loadUrl("http://kaifa.star.99hwan.com/?ct=qun&app=1&uid=wVHflX_IvVuLxNJ12HAFug==&t=1642560457&sign=21d704be9d49ce8ce791464db8d98547")
//    }
    // 适配器
    inner class Adapter:   BaseQuickAdapter<LiveRoomBean, BaseDataBindingHolder<ItemFragmentLiveBinding>>(R.layout.item_fragment_live),
        LoadMoreModule {
        override fun convert(holder: BaseDataBindingHolder<ItemFragmentLiveBinding>, item: LiveRoomBean) {
            holder.dataBinding?.data = item
            if(item.status=="1"){
                holder.dataBinding?.tvLiveState?.text = "直播中"
                holder.dataBinding?.tvLiveState?.backgroundTintList = null
            }else{
                holder.dataBinding?.tvLiveState?.text = "未直播"
                holder.dataBinding?.tvLiveState?.backgroundTintList = ColorStateList.valueOf(Color.parseColor("#575656"))
            }
            holder.itemView.setOnClickListener {
                V2TIMManager.getGroupManager().getGroupsInfo(arrayListOf(item.room_id),object :
                    V2TIMValueCallback<List<V2TIMGroupInfoResult>> {
                    override fun onSuccess(p0: List<V2TIMGroupInfoResult>?) {
                        p0?.apply {
                            Log.e(TUIUtils.TAGQUN, "onSuccess: "+p0[0].resultCode )
                            if(item.status=="1"){
                                if(p0[0].resultCode==0){
                                    LiveActivity.start(this@MyCollectActivity,item.room_id)
                                }else{
                                }
                            }else{
                                "该房间暂未开播".toast()
                            }
                        }
                    }

                    override fun onError(p0: Int, p1: String?) {
                        Log.e(TUIUtils.TAGQUN, "onError: $p0   $p1", )
                    }

                })

            }
        }
    }
//    fun exit(){
//        if(web.isVisible){
//            if (web.canGoBack()){
//                web.goBack()
//            }else{
//                finish()
//            }
//        }else{
//            finish()
//        }
//    }

}